"""
配置文件 - 系统配置管理
"""
import os
from typing import Optional
from pydantic_settings import BaseSettings
from functools import lru_cache


class Settings(BaseSettings):
    """系统配置类"""
    
    # 基础配置
    app_name: str = "MinerU 文档解析服务"
    app_version: str = "1.0.0"
    debug: bool = False
    host: str = "0.0.0.0"
    port: int = 8000
    web_port: int = 8000
    mcp_port: int = 8001
    
    # 数据库配置 
    database_url: str = "sqlite:///./app.db"
    
    # Redis配置
    redis_url: str = "redis://localhost:6379/0"
    cache_enabled: bool = True
    cache_ttl: int = 300  # 5分钟
    
    # JWT配置
    jwt_secret_key: str = "your-secret-key-change-in-production"
    jwt_algorithm: str = "HS256"
    jwt_expire_seconds: int = 3600  # 1小时
    
    # 文件上传配置
    upload_dir: str = "uploads"
    max_file_size: int = 50 * 1024 * 1024  # 50MB
    allowed_extensions: set = {".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"}
    
    # 解析结果配置
    parsed_results_dir: str = "parsed_results"
    results_retention_days: int = 90
    
    # 任务配置
    max_concurrent_tasks: int = 10
    check_pending_tasks_interval: int = 10  # 检查间隔（秒）
    task_timeout_seconds: int = 300  # 5分钟
    
    # MinerU配置
    mineru_model_path: Optional[str] = None
    mineru_device: str = "cpu"
    default_ocr_engine: str = "paddle"
    
    # 日志配置
    log_level: str = "INFO"
    log_file: str = "logs/app.log"
    server_log_file: str = "logs/server.log"
    
    # 安全配置
    cors_origins: list = ["http://localhost:3000", "http://localhost:8080", "http://127.0.0.1:3000"]
    cors_allow_credentials: bool = True
    cors_allow_methods: list = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
    cors_allow_headers: list = ["Content-Type", "Authorization", "X-CSRF-Token", "X-Requested-With"]
    
    # HTTPS配置
    ssl_certfile: Optional[str] = None
    ssl_keyfile: Optional[str] = None
    force_https: bool = False
    
    # 安全头部配置
    security_hsts_enabled: bool = True
    security_hsts_max_age: int = 31536000  # 1年
    security_hsts_include_subdomains: bool = True
    security_hsts_preload: bool = True
    default_admin_password: str = "Bovo!666"
    
    # CSP配置
    security_csp_enabled: bool = True
    security_csp_default_src: list = ["'self'"]
    security_csp_script_src: list = ["'self'", "'unsafe-inline'"]
    security_csp_style_src: list = ["'self'", "'unsafe-inline'"]
    security_csp_img_src: list = ["'self'", "data:", "https:"]
    security_csp_font_src: list = ["'self'", "data:", "https:"]
    security_csp_connect_src: list = ["'self'"]
    security_csp_frame_src: list = ["'none'"]
    security_csp_object_src: list = ["'none'"]
    
    # 其他安全头部
    security_x_frame_options: str = "DENY"
    security_x_content_type_options: str = "nosniff"
    security_x_xss_protection: str = "1; mode=block"
    security_referrer_policy: str = "strict-origin-when-cross-origin"
    security_permissions_policy: str = "camera=(), microphone=(), geolocation=()"
    
    # 限流配置
    rate_limit_requests: int = 100
    rate_limit_window: int = 60  # 秒
    
    # 系统监控配置
    enable_system_monitoring: bool = True
    save_metrics_to_db: bool = False  # 是否保存监控数据到数据库
    metrics_retention_days: int = 30  # 监控数据保留天数
    metrics_collection_interval: int = 60  # 数据收集间隔（秒）
    metrics_monitor_interval: int = 1  # 监控间隔（秒）
    
    class Config:
        env_file = ".env"
        case_sensitive = False


@lru_cache()
def get_settings() -> Settings:
    """获取配置实例（带缓存）"""
    return Settings()


def create_directories():
    """创建必要的目录"""
    settings = get_settings()
    os.makedirs(settings.upload_dir, exist_ok=True)
    os.makedirs(settings.parsed_results_dir, exist_ok=True)
    os.makedirs(os.path.dirname(settings.log_file), exist_ok=True)
    os.makedirs("logs", exist_ok=True)